package util::qqwry;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(ipwhere);

use Encode;
use utf8;
binmode(STDIN, ':encoding(utf8)');
binmode(STDOUT, ':encoding(utf8)');
binmode(STDERR, ':encoding(utf8)');

sub ipwhere {

    my $ip=shift;
    my $ipfile = shift;
    my ($ipbegin,$ipend,$ipData1,$ipData2,$DataSeek,$ipFlag);

    my @ip=split(/\./,$ip);
    my $ipNum = $ip[0]*16777216+$ip[1]*65536+$ip[2]*256+$ip[3];

#    print $ipfiel,"\n";
    open FILE,"$ipfile" or die "$!\n";
    binmode(FILE);
    sysread(FILE,$ipbegin,4);
    sysread(FILE,$ipend,4);
     $ipbegin=unpack("L",$ipbegin);
     $ipend=unpack("L",$ipend);
    my $ipAllNum = ($ipend-$ipbegin)/7+1;

    my $BeginNum=0;
    my $EndNum=$ipAllNum;

    Bgn:
    my $Middle= int(($EndNum+$BeginNum)/2);

    seek(FILE,$ipbegin+7*$Middle,0);
    read(FILE,$ipData1,4);
    my $ip1num=unpack("L",$ipData1);
    if ($ip1num > $ipNum) {
        $EndNum=$Middle;
        goto Bgn;
    }

    read(FILE,$DataSeek,3);
    $DataSeek=unpack("L",$DataSeek."\0");
    seek(FILE,$DataSeek,0);
    read(FILE,$ipData2,4);
    my $ip2num=unpack("L",$ipData2);
    if ($ip2num < $ipNum) {
        goto nd if ($Middle==$BeginNum);
        $BeginNum=$Middle;
        goto Bgn;
    }

    $/="\0";
    read(FILE,$ipFlag,1);
    if ($ipFlag eq "\1") {
        my $ipSeek;
        read(FILE,$ipSeek,3);
        $ipSeek = unpack("L",$ipSeek."\0");
        seek(FILE,$ipSeek,0);
        read(FILE,$ipFlag,1);
    }
    if ($ipFlag eq "\2") {
        my $AddrSeek;
        read(FILE,$AddrSeek,3);
        read(FILE,$ipFlag,1);
        if($ipFlag eq "\2") {
            my $AddrSeek2;
            read(FILE,$AddrSeek2,3);
            $AddrSeek2 = unpack("L",$AddrSeek2."\0");
            seek(FILE,$AddrSeek2,0);
        }
        else {
            seek(FILE,-1,1);
        }
        $ipAddr2=<FILE>;
        $AddrSeek = unpack("L",$AddrSeek."\0");
        seek(FILE,$AddrSeek,0);
        $ipAddr1=<FILE>;
    }
    else {
        seek(FILE,-1,1);
        $ipAddr1=<FILE>;
        read(FILE,$ipFlag,1);
        if($ipFlag eq "\2") {
            my $AddrSeek2;
            read(FILE,$AddrSeek2,3);
            $AddrSeek2 = unpack("L",$AddrSeek2."\0");
            seek(FILE,$AddrSeek2,0);
        }
        else {
            seek(FILE,-1,1);
        }
        $ipAddr2=<FILE>;
    }

    nd:
    chomp($ipAddr1,$ipAddr2);
    $/="\n";
    close(FILE);

    $ipAddr2="" if($ipAddr2=~/http/i);
    my $ipaddr="$ipAddr1 $ipAddr2";
    $ipaddr =~ s/CZ88\.NET//isg;
    $ipaddr="未知地区" if ($ipaddr=~/未知|http/i || $ipaddr eq "");
    return &decode("gbk",$ipaddr);
}

1;
